package com.mxpio.erp.inventory.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.inventory.entity.TransferOrder;
import com.mxpio.erp.common.inventory.entity.TransferOrderLine;
import com.mxpio.erp.common.inventory.service.TransferOrderLineService;
import com.mxpio.erp.common.inventory.service.TransferOrderService;
import com.mxpio.erp.common.jpa.model.Order;
import com.mxpio.erp.common.order.policy.OrderContext;
import com.mxpio.erp.common.order.service.OrderService;
import com.mxpio.erp.common.vo.OrderExcuteVo;
import com.mxpio.erp.inventory.policy.impl.DefaultToPolicy;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

@Tag(name = "TransferOrderController", description = "调拨接口")
@RestController
@RequestMapping("/erp/inventory/to/")
public class TransferOrderController {
	
	@Autowired
	private TransferOrderService transferOrderSerivce;
	
	@Autowired
	private TransferOrderLineService transferOrderLineSerivce;
	
	@Autowired
	private OrderService bizOrderService;

	@GetMapping("list")
	@Operation(summary = "调拨单列表", description = "获取调拨单列表", method = "GET")
	public Result<List<TransferOrder>> list(Criteria criteria) throws UnsupportedEncodingException {
		List<TransferOrder> tos = transferOrderSerivce.list(TransferOrder.class, criteria);
		return Result.OK(tos);
	}
	
	@GetMapping("page")
	@Operation(summary = "调拨单列表", description = "获取调拨单列表", method = "GET")
	public Result<Page<TransferOrder>> page(Criteria criteria, Integer pageSize, Integer pageNo) throws UnsupportedEncodingException {
		Pageable pageAble = PageRequest.of(pageNo-1, pageSize);
		Page<TransferOrder> page = transferOrderSerivce.listPage(TransferOrder.class, pageAble, criteria);
		return Result.OK(page);
	}
	
	@GetMapping("list/{bizNo}")
	@Operation(summary = "根据bizNo获取调拨单", description = "根据bizNo获取调拨单", method = "GET")
	public Result<TransferOrder> getById(@PathVariable(name = "bizNo", required = true) String bizNo) {
		TransferOrder transferOrder = transferOrderSerivce.getById(TransferOrder.class, bizNo);
		return Result.OK(transferOrder);
	}
	
	@RequestMapping("save")
    @Operation(summary = "保存调拨单", description = "保存调拨单")
    public Result<TransferOrder> save(@RequestBody TransferOrder transferOrder) {
		transferOrderSerivce.save(transferOrder,new SmartCrudPolicyAdapter(){
        	@Override
        	public boolean beforeInsert(CrudContext context) {
        		Object o = context.getEntity();
        		if(o instanceof TransferOrderLine){
        			TransferOrder transferOrder = context.getParent();
                    ((TransferOrderLine) o).setBizNo(transferOrder.getBizNo());
        		}
        		return true;
        	}
        });
        return Result.OK(transferOrder);
    }
	
/*	@RequestMapping("excute/{accessType}/{bizNo}")
    @Operation(summary = "执行调拨单", description = "执行调拨单")
    public Result<Object> excute(@PathVariable(name = "bizNo", required = true) String bizNo, 
    		@PathVariable(name = "accessType", required = true) String accessType,
    		@RequestBody OrderExcuteVo orderExcuteVo) {
		TransferOrder transferOrder = transferOrderSerivce.getById(TransferOrder.class, bizNo);
    	
    	OrderContext context = bizOrderService.execute(transferOrder, new DefaultToPolicy(orderExcuteVo.getLines(), accessType));
    	if(CollectionUtils.isEmpty(context.getErrors())) {
    		return Result.OK();
    	}else {
    		return Result.error(context.getErrors().get(0));
    	}
    }*/

	@RequestMapping("excute/{bizNo}")
	@Operation(summary = "执行调拨单", description = "执行调拨单")
	public Result<Object> excute(@PathVariable(name = "bizNo", required = true) String bizNo,
								 //@PathVariable(name = "accessType", required = true) String accessType,
								 @RequestBody OrderExcuteVo orderExcuteVo) {
		TransferOrder transferOrder = transferOrderSerivce.getById(TransferOrder.class, bizNo);

		OrderContext context = bizOrderService.execute(transferOrder, new DefaultToPolicy(orderExcuteVo.getLines()));
		if(CollectionUtils.isEmpty(context.getErrors())) {
			return Result.OK();
		}else {
			return Result.error(context.getErrors().get(0));
		}
	}

	@DeleteMapping("remove/{bizNos}")
	@Operation(summary = "删除调拨单", description = "删除调拨单", method = "DELETE")
	public Result<TransferOrder> remove(@PathVariable(name = "bizNos", required = true) String bizNos) {
		String bizNo[] = bizNos.split(",");
		for(String key : bizNo){
			Criteria c = Criteria.create().addCriterion("bizNo", Operator.EQ, key);
			transferOrderLineSerivce.removeBatch(TransferOrderLine.class, c);
			transferOrderSerivce.delete(TransferOrder.class, key);
		}
		return Result.OK();
	}
	
	@PutMapping("open/{bizNo}")
    @Operation(summary = "打开调拨单", description = "打开调拨单", method = "PUT")
    public Result<? extends Order> open(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
		Order order = transferOrderSerivce.getById(TransferOrder.class,bizNo);
    	return bizOrderService.updateCloseStatus(order, OrderStatusEnums.CloseStatus.OPEN);
    }

    @PutMapping("close/{bizNo}")
    @Operation(summary = "关闭调拨单", description = "关闭调拨单", method = "PUT")
    public Result<? extends Order> close(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	Order order = transferOrderSerivce.getById(TransferOrder.class,bizNo);
    	return bizOrderService.updateCloseStatus(order, OrderStatusEnums.CloseStatus.CLOSED);
    }
    
    @PutMapping("submit/{bizNo}")
    @Operation(summary = "提交调拨单", description = "提交调拨单", method = "PUT")
    public Result<? extends Order> submit(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	TransferOrder order = transferOrderSerivce.getById(TransferOrder.class,bizNo);
    	if(order.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode())){
    		return bizOrderService.updateBpmnStatus(order, OrderStatusEnums.BpmnStatus.AUDITING);
    	}else {
    		return Result.error("非开立状态不可提交");
		}
    }

    @PutMapping("audit/{bizNo}")
    @Operation(summary = "审核调拨单", description = "审核调拨单", method = "PUT")
    public Result<? extends Order> audit(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	TransferOrder order = transferOrderSerivce.getById(TransferOrder.class,bizNo);
    	if(order.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())){
    		return bizOrderService.updateBpmnStatus(order, OrderStatusEnums.BpmnStatus.AUDITED);
    	}else {
    		return Result.error("非审核中状态不可审核");
		}
    }

    @PutMapping("abandon/{bizNo}")
    @Operation(summary = "弃审调拨单", description = "弃审调拨单", method = "PUT")
    public Result<? extends Order> abandon(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	TransferOrder order = transferOrderSerivce.getById(TransferOrder.class,bizNo);
    	if(order.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())||order.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode())){
    		return bizOrderService.updateBpmnStatus(order, OrderStatusEnums.BpmnStatus.CREATE);
    	}else{
    		return Result.error("非审核中、已审核状态不可审核");
    	}
    }
	
}
